﻿using CustomAuthorizationDemo.Authorization;
using CustomAuthorizationDemo.DI;
using CustomAuthorizationDemo.Security.Session;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CustomAuthorizationDemo
{
    public class SamplePermissionChecker : IPermissionChecker
    {
        private readonly Dictionary<long, string[]> userPermissions = new Dictionary<long, string[]>
        {
            //Id=1的用户具有Test模块的全部功能
            { 1, new[] { PermissionNames.TestAdd, PermissionNames.TestEdit, PermissionNames.TestDelete } },
            //Id=2的用户具有Test模块的编辑和删除功能
            { 2, new[] { PermissionNames.TestEdit, PermissionNames.TestDelete } }
        };

        public IClaimsSession Session { get; }

        //通过构造函数注入IClaimsSession实例，以便在权限鉴定方法中获取用户信息
        public SamplePermissionChecker(IClaimsSession session)
        {
            this.Session = session;
        }

        public Task<bool> IsGrantedAsync(string permissionName)
        {
            if(!userPermissions.Any(p => p.Key == Session.UserId))
                return Task.FromResult(false);
            var up = userPermissions.Where(p => p.Key == Session.UserId).First();
            var granted = up.Value.Any(permission => permission.Equals(permissionName, StringComparison.InvariantCultureIgnoreCase));
            return Task.FromResult(granted);
        }

    }
}
